import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { Button, Drawer, Descriptions, Space, Skeleton, Modal, Form, Input, App } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';

import { getInfo, logout, del } from '../../apis/user.js';

const UserInfo = ({ style }) => {
  const navigate = useNavigate(); // 用于 React Router 跳转
  const { message } = App.useApp();
  const [userInfo, setUserInfo] = useState(null);
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    setUser();
  }, []);

  const setUser = async () => {
    const res = await getInfo();
    if (res.success) {
      setUserInfo(res.data);
    }
  };

  // 打开抽屉
  const showDrawer = () => {
    setVisible(true);
  };

  // 关闭抽屉
  const onClose = () => {
    setVisible(false);
  };

  const logoutUser = async () => {
    const res = await logout();
    if (res.success) {
      message.success('退出成功');
      navigate('/login');
    }
  };

  const deleteUser = async () => {
    const res = await del();
    if (res.success) {
      message.success('已经删除用户及相关数据');
      navigate('/login');
    }
  };

  const formatDate = (date)=>{
    return dayjs(date).format('YYYY-MM-DD')
  }

  const [isModalOpen, setIsModalOpen] = useState(false);

  // 显示 Modal
  const showModal = () => {
    setIsModalOpen(true);
  };

  // 关闭 Modal
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 提交表单
  const handleOk = async () => {
    try{
      await form.validateFields()
    } catch(e){
      return
    }
    await deleteUser();
  };

  return (
    <div>
      <Button onClick={showDrawer} style={style} shape="circle" icon={<UserOutlined/>} title={'个人信息'}/>

      {/* 侧拉抽屉 */}
      <Drawer
        title="个人信息"
        placement="right"
        onClose={onClose}
        open={visible}
        width={300}
      >
        {/* 用户信息描述 */}
        {userInfo ? (
          <Descriptions title="用户信息" column={1}>
            <Descriptions.Item label="用户id">{userInfo.id}</Descriptions.Item>
            <Descriptions.Item label="用户名">{userInfo.username}</Descriptions.Item>
            <Descriptions.Item label="用户邮箱">{userInfo.email}</Descriptions.Item>
            <Descriptions.Item label="加入时间">{formatDate(userInfo.createdAt)}</Descriptions.Item>
          </Descriptions>
        ) : (
          <Skeleton active/>
        )}

        {/* 操作按钮 */}
        <Space style={{ marginTop: '20px' }}>
          <Button onClick={logoutUser} type="default">登出</Button>
          <Button onClick={showModal} type="primary" danger>注销</Button>
        </Space>

        {/* Modal 框 */}
        <Modal
          title="是否彻底删除用户所有数据"
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          okText='确认'
          cancelText='取消'
        >
          {/* 表单 */}
          <Form
            form={form}
            layout="vertical" // 垂直布局
          >
            <Form.Item
              label='输入“确认删除“点击确认执行'
              name="inputValue"
              validateTrigger='onBlur'
              rules={[
                () => ({
                  validator(_, text) {
                    if(text==='确认删除'){
                      return Promise.resolve();
                    } else {
                      return Promise.reject('内容不合法');
                    }
                  },
                })
              ]}
            >
              <Input placeholder="请输入内容" />
            </Form.Item>
          </Form>
        </Modal>
      </Drawer>
    </div>
  );
};

export default UserInfo;
